package com.itheima.itcasthealth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.itcasthealth.common.Result;
import com.itheima.itcasthealth.entiry.*;
import com.itheima.itcasthealth.mapper.*;
import com.itheima.itcasthealth.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealAndCheckGroupMapper setmealAndCheckGroupMapper;

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Autowired
    private CheckGroupAndItemMapper checkGroupAndItemMapper;

    @Autowired
    private CheckItemMapper checkItemMapper;

    @Cacheable(value = "Setmeal",key = "'all'")
    @Override
    public Result getAllSetmeal() {

        List<Setmeal> setmeals = setmealMapper.selectList(null);

        return new Result(true,"查询成功",setmeals);
    }

    @Cacheable(value = "Setmeal",key = "#id")
    @Override
    public Result findById(Integer id) {
        Integer[] checkGroupIdsBySetmealIds = setmealAndCheckGroupMapper.findCheckGroupIdsBySetmealId(id);

        Setmeal setmeal = setmealMapper.selectById(id);


        LambdaQueryWrapper<CheckGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CheckGroup::getId,checkGroupIdsBySetmealIds);
        List<CheckGroup> checkGroups = checkGroupMapper.selectList(wrapper);
        for (CheckGroup checkGroup : checkGroups) {
            Integer[] checkItemIdsByCheckGroupIds = checkGroupAndItemMapper.findCheckItemIdsByCheckGroupId(checkGroup.getId());
            LambdaQueryWrapper<CheckItem> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(CheckItem::getId,checkItemIdsByCheckGroupIds);
            List<CheckItem> checkItems = checkItemMapper.selectList(wrapper1);
            checkGroup.setCheckItems(checkItems);
        }
        setmeal.setCheckGroups(checkGroups);
        return new Result(true,"查询成功",setmeal);
    }
}
